# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-08-20 15:41:37
LastEditors: peng2.zhang
LastEditTime: 2021-12-17 14:38:57
'''
from kafka import KafkaProducer
import os
import re
import json
import yaml
import inspect
from os.path import abspath, dirname
base_path = abspath(dirname(__file__))
from ci_conclude.const import JenkinsServer

class BaseConclude():
    def __init__(self, project_name, buildid, stage_id=0, stage_name="", git_name="", git_token="", git_commit_id="", git_branch_name="", eureka_app_name="", bootstrap_servers=None, kafka_topic="test"):
        self.project_name = project_name
        self.product = self.project_name.split("_")[0]
        self.buildid = buildid
        self.stage_id = stage_id
        self.stage_name = stage_name
        self.jenkins_url = f"{JenkinsServer.DEFAULT.NAME}/view/{self.product}/job/{self.project_name}/{self.buildid}/"
        self.junit_result_url = f"{JenkinsServer.DEFAULT.NAME}/view/{self.product}/job/{self.project_name}/{self.buildid}/testReport/"
        self.allure_result_url = f"{JenkinsServer.DEFAULT.NAME}/view/{self.product}/job/{self.project_name}/{self.buildid}/allure/"
        self.topic = kafka_topic
        self.git_name = git_name
        if ".git" in self.git_name:
            self.search_git_name = self.eureka_app_name = re.compile("(\S+)\.git").findall(self.git_name.split("/")[-1])[0]
        else:
            self.search_git_name = self.eureka_app_name = self.git_name
        if eureka_app_name:
            self.eureka_app_name = eureka_app_name
        self.git_commit_id = git_commit_id if git_commit_id else ""
        self.git_branch_name = git_branch_name if git_branch_name else ""
        self.git_token = git_token
        # self.config_path = os.path.join(base_path, "conf", "ci_conclude.yaml")
        # with open(self.config_path, "r") as f:
        #     self.config = yaml.load(f)
        print("#"* 50)
        print(bootstrap_servers)
        print("#"* 50)

        try:
            if bootstrap_servers:
                bootstrap_server_list = bootstrap_servers.split(",")
                self.producer = KafkaProducer(bootstrap_servers=bootstrap_server_list,
                    value_serializer=lambda x: str(x).encode('utf-8'),
                    key_serializer=lambda x: str(x).encode('utf-8'))
            else:
                self.producer = None
        except Exception as e:
            self.producer = None
    
    def get_url(self):
        raise NotImplementedError()

    @property
    def _get_url_need_path(self):
        arg_spec = inspect.getargspec(self.get_url)
        args = arg_spec.args
        args_without_self = [x for x in args if x != 'self']
        if len(args_without_self) > 0:
            return True
        else:
            return False

    def get_result(self):
        raise NotImplementedError()
    
    def format_to_weixin(self, result_kwargs, url):
        return ""

    @property
    def _get_result_need_path(self):
        arg_spec = inspect.getargspec(self.get_result)
        args = arg_spec.args
        args_without_self = [x for x in args if x != 'self']
        if len(args_without_self) > 0:
            return True
        else:
            return False
    def upload_result(self, url, result_kwargs, code=0, message="PASS"):
        result_kwargs["data"].update(
            job_name=self.project_name,
            build_id=self.buildid,
            stage_id=self.stage_id,
            stage_name=self.stage_name,
            url=url,
        )

        # kw = {
        #     "code": code,
        #     "message": message,
        #     "data":{
        #         "job_name": self.project_name,
        #         "build_id": self.buildid,
        #         "stage_id": self.stage_id,
        #         "stage_name": self.stage_name,
        #         "result": result_kwargs,
        #         "url": url,
        #         "file": data,
        #         "file_name": file_name
        #     }
        # }
        print(result_kwargs)
        if not self.producer:
            raise NotImplementedError()
        self.producer.send(self.topic, value=json.dumps(result_kwargs))
